<!-- 箱包申请 -->
<template>
    <!-- #ifdef H5 -->
    <uni-nav-bar title="箱包申请" :statusBar="true" fixed :border="false" leftIcon="left"
                 backgroundColor="#4BA9FB" color="#FFFFFF" @clickLeft="commonUtils.finish">
    </uni-nav-bar>

    <!-- 顶部内容 -->
    <u-sticky>
        <view class="topContent">
            <!-- 日期选择 -->
            <view class="dateContent" v-if="pageType === '0'" @click="isShowDatePicker = true">
                <image class="dateIcon" src="@/static/images/date_icon.png" mode="scaleToFill"/>
                <view class="dateTxt">{{ selectDate }}</view>
            </view>

            <!-- 部门名称 -->
            <view class="deptName" v-if="pageType === '1'">
                {{ deptName }}
            </view>
        </view>
    </u-sticky>
    <!-- #endif -->

    <!-- #ifndef H5 -->
    <u-sticky>
        <uni-nav-bar title="箱包申请" :statusBar="true" fixed :border="false" leftIcon="left"
                     backgroundColor="#4BA9FB" color="#FFFFFF" @clickLeft="commonUtils.finish">
        </uni-nav-bar>

        <!-- 顶部内容 -->
        <view class="topContent">
            <!-- 日期选择 -->
            <view class="dateContent" v-if="pageType === '0'" @click="isShowDatePicker = true">
                <image class="dateIcon" src="@/static/images/date_icon.png" mode="scaleToFill"/>
                <view class="dateTxt">{{ selectDate }}</view>
            </view>

            <!-- 部门名称 -->
            <view class="deptName" v-if="pageType === '1'">
                {{ deptName }}
            </view>
        </view>
    </u-sticky>
    <!-- #endif -->

    <!-- 列表内容 -->
    <view class="boxList">
        <view class="boxItem" v-for="(item,index) in boxList" :key="index" @click="onCashBoxItemClick(item)">
            <view class="boxName">{{ item.name }}</view>
            <image class="boxCheck" v-if="item.isSelected" src="@/static/images/check_select.png" mode="widthFix"/>
            <image class="boxCheck" v-else src="@/static/images/check_normal.png" mode="widthFix"/>
        </view>
    </view>

    <!--备注-->
    <view class="remarkLayout">
        <textarea class="remark" :value="inputRemark" placeholder="备注（可输入备注内容）" @input="onInputRemarkChange"
                  placeholder-style="color:#999999;" auto-height cursor-spacing="130">
        </textarea>
    </view>

    <!--按钮-->
    <view class="btnContent">
        <view class="btnCommit" v-if="pageType === '0'" @click="onCommitClick">提交申请</view>
        <view class="btnCommit" v-if="boxStatus" @click="onModifyClick">修改申请</view>
        <view class="btnCommit" v-if="boxStatus" @click="onRevokeClick">撤回申请</view>
    </view>

    <!-- 日期选择器 -->
    <u-datetime-picker ref="datetimePickerRef" :show="isShowDatePicker" v-model="datePickerDateTime" mode="date"
                       :formatter="formatter" @cancel="isShowDatePicker = false" @confirm="onDateConfirm">
    </u-datetime-picker>
</template>

<script setup>
import {ref} from "vue";
import {onLoad, onReady} from "@dcloudio/uni-app";
import dayjs from "dayjs";
import {myStore} from "@/stores";
import {
    addTaskRequest,
    cashBoxQueryListRequest,
    modifyTaskRequest, queryApplyedBoxRequest,
    reBackTaskRequest
} from "@/net/Api";
import commonUtils from "@/utils/commonUtils";

const store = myStore()
const datePickerDateTime = ref(Date.now())
const selectDate = ref(dayjs(Date.now()).format("YYYY-MM-DD"))
const isShowDatePicker = ref(false)
const datetimePickerRef = ref(null)
const pageType = ref('')
const deptId = ref('')
const boxList = ref([])
const applyedBoxList = ref([])
const boxStatus = ref('')
const boxStatusVal = ref('')
const inputRemark = ref('')
const deptName = ref('')
const taskId = ref('')

onLoad(async (options) => {
    pageType.value = options.pageType
    // 申请款箱
    if (options.pageType === '0') {
        selectDate.value = dayjs().format('YYYY-MM-DD')
        deptId.value = store.deptId
    }
    // 修改申请、撤回申请
    else {
        //任务详情
        let itemData = JSON.parse(decodeURIComponent(options.itemData))
        console.log("itemData = ", itemData)
        boxStatus.value = itemData.prepareStatus === '0' //'0 未备箱'  '1 已备箱'
        boxStatusVal.value = itemData.prepareStatus //'0 未备箱'  '1 已备箱'
        inputRemark.value = itemData.comment
        deptName.value = itemData.applyDeptName
        deptId.value = itemData.applyDeptId
        taskId.value = itemData.id

        queryApplyedBox()
        selectDate.value = dayjs(itemData.createTime).format('YYYY-MM-DD')
    }

    await cashBoxQueryList()
})

onReady(() => {
    // 微信小程序需要用此写法
    datetimePickerRef.value.setFormatter(formatter);
})

/**
 * 日期格式化
 */
const formatter = (type, value) => {
    if (type === 'year') {
        return `${value}年`;
    }
    if (type === 'month') {
        return `${value}月`;
    }
    if (type === 'day') {
        return `${value}日`;
    }
    return value;
}

/**
 * 日期选择器确认事件
 */
const onDateConfirm = (e) => {
    isShowDatePicker.value = false
    datePickerDateTime.value = e.value
    selectDate.value = dayjs(e.value).format("YYYY-MM-DD")
    cashBoxQueryList()
}


/**
 * 选择款箱条目
 */
const onCashBoxItemClick = (selectItem) => {
    boxList.value = boxList.value.map((item) => {
        if (selectItem.id == item.id) {
            item.isSelected = !item.isSelected
        }
        return item
    })
}

/**
 * 输入备注
 */
const onInputRemarkChange = (e) => {
    inputRemark.value = e.detail.value
}

/**
 * 提交申请
 */
const onCommitClick = () => {
    addTask()
}

/**
 * 修改申请
 */
const onModifyClick = () => {
    modifyTask()
}

/**
 * 撤回申请
 */
const onRevokeClick = () => {
    let that = this
    uni.showModal({
        title: '撤回申请',
        content: '确定要撤回申请吗？',
        success: function (res) {
            if (res.confirm) {
                reBackTask()
            } else if (res.cancel) {

            }
        }
    })
}

/**
 * 获取所有款箱列表
 */
const cashBoxQueryList = async () => {
    let params = {
        deptId: store.deptId,
        status: "1", //	款箱启用状态0禁用1启用
        type: "",//	款箱类型 字典值
        locationStatus: ""//位置状态(字典) 0未知(灰色) 1在库(蓝色) 2离库(黄色) 3在押(褐色) 4网点(绿色) 5外库(蓝色)
    }
    await cashBoxQueryListRequest(params).then((res) => {
        uni.hideLoading()
        let boxArr = res.data?.map((item) => {
            return {
                ...item,
                isSelected: false
            }
        })

        boxArr.forEach((item) => {
            applyedBoxList.value.forEach((subItem) => {
                if (item.id === subItem.cashboxId) {
                    item.isSelected = true
                }
            })
        })
        console.log("boxArr = ", boxArr)
        boxList.value = boxArr
    }).catch((err) => {
        uni.hideLoading()
    })
}

/**
 * 新增款箱申请
 */
const addTask = () => {
    let selectedBoxArr = boxList.value.filter(item => item.isSelected).map(item => item.id);
    if (selectedBoxArr.length == 0) {
        uni.showToast({
            title: '请选择款箱',
            icon: 'none'
        })
        return
    }

    let params = {
        applyDay: selectDate.value,
        applyDeptId: store.deptId,
        applyCashboxIdList: selectedBoxArr,
        comment: inputRemark.value,
    }

    uni.showLoading()
    addTaskRequest(params).then((res) => {
        uni.hideLoading()
        uni.showToast({
            title: '申请成功',
            icon: 'none'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 500)
    }).catch((err) => {
        uni.hideLoading()
    })
}

/**
 * 修改款箱申请
 */
const modifyTask = () => {
    let selectedBoxArr = boxList.value.filter(item => item.isSelected).map(item => item.id);
    if (selectedBoxArr.length == 0) {
        uni.showToast({
            title: '请选择款箱',
            icon: 'none'
        })
        return
    }

    let params = {
        // applyDay: selectDate.value,
        // applyDeptId: deptId.value,
        id: taskId.value,
        comment: inputRemark.value,
        prepareStatus: boxStatusVal.value,
        applyCashboxIdList: selectedBoxArr,
    }

    uni.showLoading()
    modifyTaskRequest(params).then((res) => {
        uni.hideLoading()
        uni.showToast({
            title: '修改成功',
            icon: 'none'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 500)
    }).catch((err) => {
        uni.hideLoading()
    })
}

/**
 * 撤回款箱申请
 */
const reBackTask = () => {
    let params = {
        id: taskId.value
    }
    uni.showLoading()
    reBackTaskRequest(params).then((res) => {
        uni.hideLoading()
        uni.showToast({
            title: '撤回成功',
            icon: 'none'
        })
        setTimeout(() => {
            uni.navigateBack()
        }, 500)
    }).catch((err) => {
        uni.hideLoading()
    })
}

/**
 * 根据id查询任务申请的款箱
 */
const queryApplyedBox = () => {
    let params = {
        id: taskId.value
    }
    uni.showLoading()
    queryApplyedBoxRequest(params).then((res) => {
        uni.hideLoading()
        applyedBoxList.value = res.data
    }).catch((err) => {
        uni.hideLoading()
    })
}
</script>

<style scoped lang="scss">

.topContent {
    width: 100%;
    border-bottom: 1rpx solid #F1F1F1;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    padding: 20rpx;
    background-color: #FFFFFF;
}

.dateContent {
    display: flex;
    align-items: center;
    border-radius: 50rpx;
    border: 1rpx solid #DDDDDD;
    box-sizing: border-box;
    padding: 10rpx 50rpx;
    margin-left: 10rpx;
}

.dateIcon {
    width: 60rpx;
    height: 60rpx;
}

.dateTxt {
    font-size: 34rpx;
    color: #333333;
    margin-left: 10rpx;
}

.deptName {
    font-size: 34rpx;
    color: #333333;
    font-weight: bold;
}

.boxList {
    height: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
}

.boxItem {
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 30rpx;
    border-bottom: 1rpx solid #F1F1F1;
    background-color: #FFFFFF;
}

.boxName {
    font-size: 32rpx;
    color: #333333;
}

.boxCheck {
    width: 40rpx;
    height: 40rpx;
}

.remarkLayout {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.remark {
    width: 93%;
    min-height: 200rpx;
    background-color: #fdfdf3;
    border: 1rpx solid #EEEEEE;
    border-radius: 20rpx;
    margin-top: 30rpx;
    box-sizing: border-box;
    padding: 30rpx;
}

.btnContent {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    padding: 30rpx;
}

.btnCommit {
    width: 40%;
    height: 80rpx;
    line-height: 80rpx;
    color: #FFFFFF;
    font-size: 32rpx;
    background-color: $themeColor;
    margin: 30rpx 20rpx;
    text-align: center;
    border-radius: 15rpx;
    letter-spacing: 1rpx;
}
</style>